﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Text.RegularExpressions;
using System.Net;
using System.IO;

namespace Devfw.OpenAuth.Platform
{
    public class Kaixin001
    {
        private const string defaultUrl = "http://www.kaixin001.com/";
        private const string loginUrl = "http://www.kaixin001.com/login/login_api.php";
        private const string recordUrl = "http://www.kaixin001.com/!record/index.php";
        private const string recordSubmitUrl = "http://www.kaixin001.com/record/submit.php";
        private const string uploadUrl = "http://www.kaixin001.com/record/upload_pic.php";
        private const string statusUrl = "http://www.kaixin001.com/friend/status_submit.php";
        private Encoding encoding = Encoding.UTF8;

        public Kaixin001( string userID, string password )
        {
            this.UserID = userID;
            this.Password = password;
        }

        public string UserID
        {
            get;
            set;
        }

        public string Password
        {
            get;
            set;
        }
        protected ResponseContent LoginResult
        {
            get;
            set;
        }

        //登录验证
        public bool Verify()
        {
            
            string account = this.UserID;
            string password = this.Password;
            

            // 登录
            ResponseContent defaultResult = Common.GetUrl(defaultUrl, encoding, null, "GET", string.Empty);
            Match reLoginKey = Regex.Match( defaultResult.content, @"new EnLogin[^\w]{1,100}(\w+)", RegexOptions.IgnoreCase );
            string loginKey = reLoginKey.Groups[1].Value;
            
            KaixinEncode LoginMgr = new KaixinEncode();
            
            string loginContent = string.Format( "ver=1&email={0}&rpasswd={1}&encypt={2}&url=%2Fhome%2F",
                    HttpUtility.UrlEncode( account ),
                    HttpUtility.UrlEncode( LoginMgr.enp( password, loginKey ) ),
                    HttpUtility.UrlEncode( loginKey )
                );
            
            LoginResult = Common.GetUrl(loginUrl, encoding, defaultResult.cookies, "POST", loginContent);

            return !LoginResult.content.Contains( "errno" );
            
        }

        

        /// <summary>
        /// 发布状态
        /// </summary>
        /// <param name="status">状态信息</param>
        /// <returns></returns>
        public ResponseContent status_submit( string status )
        {
            if (LoginResult == null)
                return null;

            string statusContent = string.Format( "state={0}",
                    HttpUtility.UrlEncode( status )
                );
            return Common.GetUrl(statusUrl, encoding, LoginResult.cookies, "POST", statusContent);
        }


        /// <summary>
        /// 发布文本记录
        /// </summary>
        /// <param name="word"></param>
        /// <param name="privacy"></param>
        /// <returns></returns>
        public ResponseContent record_submit(string word, KaixinRecordPrivacy privacy)
        {
            return record_submit(word,string.Empty, privacy);
        }

        

        /// <summary>
        /// 发布记录
        /// </summary>
        /// <param name="word">记录文本</param>
        /// <param name="filepath">图片路径</param>
        /// <param name="privacy">发布记录类型</param>
        /// <returns></returns>
        public ResponseContent record_submit(string word, string filepath, KaixinRecordPrivacy privacy)
        {

            if (LoginResult == null)
                return null;

            ResponseContent recordResult = Common.GetUrl(recordUrl, encoding, LoginResult.cookies, "GET", string.Empty);
            Match reVerify = Regex.Match(recordResult.content, @"verify=([\w_]+)", RegexOptions.IgnoreCase);
            string verify = reVerify.Groups[1].Value;

            string imgstr = string.Empty;

            //上传图片
            if (!string.IsNullOrEmpty(filepath))
            {
                string phoneurl = uploadUrl + "?verify=" + verify;

                string header = string.Format(@"
------------ei4KM7KM7GI3ei4ei4ei4Ef1cH2cH2
Content-Disposition: form-data; name=""Filename""

{0}
------------ei4KM7KM7GI3ei4ei4ei4Ef1cH2cH2
Content-Disposition: form-data; name=""Filedata""; filename=""{0}""
Content-Type: application/octet-stream

", Path.GetFileName(filepath));

                string footer = @"
------------ei4KM7KM7GI3ei4ei4ei4Ef1cH2cH2
Content-Disposition: form-data; name=""Upload""

Submit Query
------------ei4KM7KM7GI3ei4ei4ei4Ef1cH2cH2--";

                byte[] uploadData = Common.GetPhotoContent(filepath,header,footer);

                ResponseContent uploadResult = Common.GetUrl(phoneurl, encoding, LoginResult.cookies, "POST", uploadData, true);

                string tempstr = uploadResult.content;
                tempstr = tempstr.Replace(@"\/", "/");
                //imgstr = tempstr.Split(new char[] { ',' })[1].Split(new char[] { ':' })[1].Replace("\"","");
                imgstr = Regex.Match(tempstr, @"((\w+/)+)(\w){1,100}_(\w+).(\w+)", RegexOptions.IgnoreCase).Groups[0].Value;
            }


            string recordSubmitContent = string.Format("verify={0}&rcode=&imgstr={1}&imgrotate=0&word={2}&privacy={3}",
                    HttpUtility.UrlEncode(verify),
                    imgstr,
                    HttpUtility.UrlEncode(word),
                    (int)privacy
                );
            ResponseContent recordSubmitResult =Common.GetUrl(recordSubmitUrl, encoding, LoginResult.cookies, "POST", recordSubmitContent);

            return recordSubmitResult;
        }


        public ResponseContent record_submitwithimg(string word, string filename,byte[] uploadData, KaixinRecordPrivacy privacy)
        {

            if (LoginResult == null)
                return null;

            ResponseContent recordResult = Common.GetUrl(recordUrl, encoding, LoginResult.cookies, "GET", string.Empty);
            Match reVerify = Regex.Match(recordResult.content, @"verify=([\w_]+)", RegexOptions.IgnoreCase);
            string verify = reVerify.Groups[1].Value;

            string imgstr = string.Empty;

            //上传图片
            if (uploadData!=null)
            {
                string phoneurl = uploadUrl + "?verify=" + verify;

                string header = string.Format(@"
------------ei4KM7KM7GI3ei4ei4ei4Ef1cH2cH2
Content-Disposition: form-data; name=""Filename""

{0}
------------ei4KM7KM7GI3ei4ei4ei4Ef1cH2cH2
Content-Disposition: form-data; name=""Filedata""; filename=""{0}""
Content-Type: application/octet-stream

", filename);

                string footer = @"
------------ei4KM7KM7GI3ei4ei4ei4Ef1cH2cH2
Content-Disposition: form-data; name=""Upload""

Submit Query
------------ei4KM7KM7GI3ei4ei4ei4Ef1cH2cH2--";

                uploadData = Common.GetPhoto(header, footer, uploadData);

                ResponseContent uploadResult = Common.GetUrl(phoneurl, encoding, LoginResult.cookies, "POST", uploadData, true);

                string tempstr = uploadResult.content;
                tempstr = tempstr.Replace(@"\/", "/");
                //imgstr = tempstr.Split(new char[] { ',' })[1].Split(new char[] { ':' })[1].Replace("\"","");
                imgstr = Regex.Match(tempstr, @"((\w+/)+)(\w){1,100}_(\w+).(\w+)", RegexOptions.IgnoreCase).Groups[0].Value;
            }


            string recordSubmitContent = string.Format("verify={0}&rcode=&imgstr={1}&imgrotate=0&word={2}&privacy={3}",
                    HttpUtility.UrlEncode(verify),
                    imgstr,
                    HttpUtility.UrlEncode(word),
                    (int)privacy
                );
            ResponseContent recordSubmitResult =Common.GetUrl(recordSubmitUrl, encoding, LoginResult.cookies, "POST", recordSubmitContent);

            return recordSubmitResult;
        }

    }

    
}
